<template>
    <div class="table-container">
        <div class="filter-container">
            <CustomDatePicker v-model="dateRange" :max-days="4" :disabled="isLoading"></CustomDatePicker>
            <el-select multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="2" v-model="selectedColumns"
                placeholder="Select" style="width: 13.5rem;margin-right: 1rem;">
                <el-option-group v-for="group in columnGroups" :key="group.label" :label="group.label">
                    <el-option v-for="item in group.options" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-option-group>
            </el-select>
            <el-button @click="handleReset" type="danger" :disabled="isLoading">重置</el-button>
            <el-button style="margin-left: auto;" :loading="isExporting"
                :disabled="isExporting || isLoading || !tableData.length" @click="handleExport" type="success">
                <template #icon>
                    <i class="fa fa-download"></i>
                </template>
                导出
            </el-button>
        </div>

        <vxe-table v-loading="isLoading" align="center" ref="tableRef" :data="currentPageData"
            :empty-text="isLoading ? '加载中...' : '暂无数据'" @sort-change="handleSortChange">
            <vxe-column type="seq" width="70" :seq-method="getSerialNumber"></vxe-column>
            <vxe-column v-for="column in visibleColumns" :key="column.prop" :field="column.prop" :title="column.label"
                sortable></vxe-column>
        </vxe-table>

        <vxe-pager v-show="tableData.length > 0" v-model:currentPage="pageVO.currentPage"
            v-model:pageSize="pageVO.pageSize" :total="pageVO.total" :layouts="[
                'Home',
                'PrevJump',
                'PrevPage',
                'Number',
                'NextPage',
                'NextJump',
                'End',
                'Sizes',
                'Total'
            ]" @page-change="handlePageChange">
        </vxe-pager>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue';
import { getMeterDetailApi } from '@/api/meter';
import dayjs from 'dayjs';
import CustomDatePicker from '@/components/header/CustomDatePicker.vue';
import { useColumnSelect } from './hooks/useColumnSelector';

const props = defineProps({
    currentMeter: {
        type: Object,
        required: true
    }
});

// 数据相关
const tableData = ref([]);
const sortConfig = ref({
    field: '',
    order: ''
});
let {
    selectedColumns,
    columnGroups,
    visibleColumns,
    columnReset
} = useColumnSelect();
// 状态控制
const isLoading = ref(false);
const isExporting = ref(false);
const tableRef = ref(null);

// 分页配置
const pageVO = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0
});

// 时间范围
const defautTimeRange = [
    dayjs().subtract(2, 'day').startOf('day').valueOf(),
    dayjs().startOf('day').valueOf()
];
const dateRange = ref(defautTimeRange);



// 处理数据，计算用量
function processData(data) {
    if (!Array.isArray(data) || data.length === 0) return [];

    // 按时间排序，确保计算用量的顺序正确
    const sortedData = data.sort((a, b) => dayjs(a.time).valueOf() - dayjs(b.time).valueOf());

    return sortedData.map((item, index) => {
        const prevReading = index > 0 ? sortedData[index - 1].value : null;
        const usage = prevReading !== null ? Number(item.value) - Number(prevReading) : null;

        return {
            ...item,
            time: dayjs(item.time).format('MM-DD HH:mm'),
            usage: usage !== null ? usage.toFixed(2) : '--',
        };
    });
}

// 计算当前页数据
const currentPageData = computed(() => {
    let sortedData = [...tableData.value];

    // 排序处理
    if (sortConfig.value.field && sortConfig.value.order) {
        sortedData.sort((a, b) => {
            const aVal = a[sortConfig.value.field];
            const bVal = b[sortConfig.value.field];
            const order = sortConfig.value.order === 'desc' ? -1 : 1;

            if (sortConfig.value.field === 'usage' && (aVal === null || bVal === null)) {
                // 处理用量为空的情况
                return aVal === null ? 1 : -1;
            }

            return aVal > bVal ? order : -order;
        });
    }

    // 分页处理
    const startIndex = (pageVO.value.currentPage - 1) * pageVO.value.pageSize;
    const endIndex = startIndex + pageVO.value.pageSize;

    return sortedData.slice(startIndex, endIndex);
});

// 监听器
watch([
    () => props.currentMeter,
    () => dateRange.value
], async ([newMeter, newDateRange], [oldMeter, oldDateRange]) => {
    if (!newMeter) return;

    // 检查是否需要重新获取数据
    const meterChanged = !oldMeter || newMeter.id !== oldMeter.id;
    const dateChanged = !oldDateRange ||
        newDateRange[0] !== oldDateRange[0] ||
        newDateRange[1] !== oldDateRange[1];

    if (meterChanged || dateChanged) {
        await fetchMeterList();
    }
});

// 方法定义
async function fetchMeterList() {
    if (!props.currentMeter?.id) return;

    isLoading.value = true;
    tableData.value = [];

    try {
        const res = await getMeterDetailApi({
            id: props.currentMeter.id,
            start_time: dateRange.value[0].valueOf(),
            end_time: dateRange.value[1].valueOf()
        });

        if (res.code === 200) {
            // 处理数据，计算用量
            const processedData = processData(res.meter_readings || []);
            console.log('processedData:', processedData);

            tableData.value = processedData;
            pageVO.value.total = processedData.length;
            pageVO.value.currentPage = 1;

            if (processedData.length === 0) {
                ElMessage.warning('所选时间范围内无数据');
            }
        } else {
            throw new Error(res.message || '获取数据失败');
        }
    } catch (error) {
        console.error('获取表计数据失败:', error);
        ElNotification({
            title: '请求失败',
            message: error.message || '服务器错误，请稍后重试',
            type: 'error',
            duration: 5000
        });
    } finally {
        isLoading.value = false;
    }
}

function handlePageChange({ currentPage, pageSize }) {
    pageVO.value.currentPage = currentPage;
    pageVO.value.pageSize = pageSize;
}

function handleSortChange({ property, order }) {
    sortConfig.value.field = property;
    sortConfig.value.order = order;
}

function handleReset() {
    dateRange.value = defautTimeRange;
    sortConfig.value = { field: '', order: '' };
    pageVO.value.currentPage = 1;
    const table = tableRef.value;
    table?.clearSort();
    columnReset()
}
async function handleExport() {
    if (!tableData.value.length) {
        ElMessage.warning('暂无数据可导出');
        return;
    }

    try {
        isExporting.value = true;
        const table = tableRef.value;
        await table?.exportData({
            filename: `${props?.currentMeter?.meter_code || '未知表计'}_${dayjs().format('YYYY-MM-DD')}_统计报表`,
            type: 'xlsx',
            mode: 'all',
            useStyle: true,
            //使用样式
            data: tableData.value,  // 直接传入完整数据
        });
    } catch (error) {
        console.error('导出失败:', error);
        ElMessage.error('导出失败，请重试');
    } finally {
        isExporting.value = false;
    }
}

function getSerialNumber({ rowIndex }) {
    return (pageVO.value.currentPage - 1) * pageVO.value.pageSize + rowIndex + 1;
}

// 生命周期
onMounted(() => {
    if (props.currentMeter) {
        fetchMeterList();
    }
});
</script>

<style scoped>
.table-container {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.filter-container {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1.2rem;
    flex-shrink: 0;
}

:deep(.vxe-table) {
    flex: 1;
    overflow: auto;
}

:deep(.vxe-pager) {
    margin-top: 1rem;
    flex-shrink: 0;
}

/* 添加用量负值的样式 */
.text-red-500 {
    color: #ef4444;
}

.text-gray-400 {
    color: #9ca3af;
}
</style>